<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>封装addEvent</title>
    <style>
        div {
            width: 100px;
            height: 100px;
            background-color: #000;
        }
    </style>
</head>
<body>
    <div></div>
</body>
<script>
    /**
     * 封装事件处理函数
     * 解决兼容性问题
     * @Author   hflxhn.com
     * @DateTime 2019-11-03T16:17:23+0800
     * @param    {obj}                 elem  绑定在谁身上
     * @param    {str}                 type   事件类型
     * @param    {fun}                 handle 事件处理函数
     */
    function addEvent(elem, type, handle) {
        if (elem.addEventListener) {
            elem.addEventListener(type, handle, false);
        }else if(elem.attachEvent) {
            elem.attachEvent('on' + type, handle);
        }else{
            elem['on' + type] = handle;
        }
    }

    var div = document.getElementsByTagName('div')['0'];
    addEvent(div, 'click', function (){
        console.log(111)
    })
</script>
</html>
